<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class User_c extends CI_Controller {
        public function __construct() {
            parent::__construct();
            $this->load->model(array('user_m', 'groups_m', 'role_m'));
            $this->load->helper(array('url', 'form', 'html'));
            $this->load->library(array('upload', 'form_validation', 'pagination', 'Datatables', 'table'));
        }
        
        public function index() {
            $data['body_id'] = 'admin_users';
            $data['title'] = 'User'; 
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');

            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/users_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
//        function user_list() {
//            $this->datatables
//                ->select('status, idno, fname, mname, lname, email, type, course, department, rolename')
//                ->from('user')
//                ->join('user_role', 'user.user_id=user_role.user_id')
//                ->join('role', 'user_role.role_id=role.role_id')
//                ->where('status', 'active')
//                ->where('idno !=', $this->session->userdata('idno'))
//                ->unset_column('department')
//                ->edit_column('course', '$1$2', 'department, course')
//                ->edit_column('status', '$1', 'idno')
//                ->add_column('edit', '<a href="user/edit/$1">Edit</a>', 'idno')
//                ->add_column('delete', anchor('user/delete/$1', 'Delete', array('onClick' => "return confirm('Are you sure you want to delete this user?')")), 'idno');
//            echo $this->datatables->generate();
//        }
        
        function user_list() {
            $this->datatables
                ->select('status, idno, fname, mname, lname, email, type, course, department, rolename')
                ->from('user')
                ->join('user_role', 'user.user_id=user_role.user_id')
                ->join('role', 'user_role.role_id=role.role_id')
                ->where('status', 'active')
                ->where('idno !=', $this->session->userdata('idno'))
                ->unset_column('department')
                ->edit_column('course', '$1$2', 'department, course')
                ->edit_column('status', '$1', 'idno')
                ->add_column('edit', anchor('user/edit/$1', 'Edit'), 'idno')
                ->add_column('delete', anchor('user/delete/$1', 'Delete', array('onClick' => "return confirm('Are you sure you want to delete this user?')")), 'idno');
            echo $this->datatables->generate();
        }
        
        function upload() {
            $data['body_id'] = 'admin_upload_user';
            $data['title'] = 'Upload Students/Employees'; 
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/upload_stud_emp_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function upload_file() {
            $data['body_id'] = 'admin_upload_user';
            if($_FILES['userfile']['name']!=""){
              $config['upload_path'] = './uploads/';
              $config['allowed_types'] = 'txt|csv'; 
  //            $config['max_size'] = '100';
  //            $config['max_width'] = '1024';
  //            $config['max_height'] = '768';
  //            $config['overwrite'] = FALSE; //If the file exists it will be saved with a progressive number appended

              $this->upload->initialize($config);

              if( ! $this->upload->do_upload()){
                  $this->session->set_flashdata('error',  $this->upload->display_errors('',''));
                  redirect(base_url().'users');
              } else {
                //If upload successful
                $file_name = $this->upload->file_name;
                
                $linesToAdd = file("./uploads/" .$file_name);
                $fp = fopen("./uploads/" .$file_name, 'w');
                if(!empty($_POST['student'])) {//student
                  fwrite($fp, "idno,fname,mname,lname,email,course,\n");
                } else {
                  fwrite($fp, "idno,fname,mname,lname,email,department,\n");
                }
                foreach($linesToAdd as $line) {
                    fwrite($fp,$line);
                }
                fclose($fp);
                
                
                $this->load->library('csvreader');
    
                $filePath = './uploads/' . $file_name;

                $data['csvData'] = $this->csvreader->parse_file($filePath);
                
                $data['error'] = $this->session->flashdata('error');
                $data['success'] = $this->session->flashdata('success');

                if(!empty($_POST['student'])) {//student
                    $data['title'] = 'Uploaded Students';
                    $this->load->view('administrator/fragments/header_v', $data);
                    $this->load->view('administrator/fragments/user_navigation_v', $data);
                    $this->load->view('administrator/uploaded_stud_v', $data);
                    $this->load->view('administrator/fragments/footer_v', $data);
                } else {
                    $data['title'] = 'Uploaded Employees';
                    $this->load->view('administrator/fragments/header_v', $data);
                    $this->load->view('administrator/fragments/user_navigation_v', $data);
                    $this->load->view('administrator/uploaded_emp_v', $data);
                    $this->load->view('administrator/fragments/footer_v', $data);
                }
              }
            } else {
              $this->session->set_flashdata('error',  'Please choose a file to upload.');
              redirect(base_url().'user/upload_file');
            }
        }
                
        function register_stud() {
            if (isset($_POST['user']) && sizeof($_POST['user'])) {
              $users = array();
              $x = 0;
              foreach ($_POST['user'] as $user)  {
                  $user = str_replace("???"," ",$user);
                  $value = explode(",", $user);
                  $users[$x] = $value;
                  $x++;
              }
                $this->user_m->insert_stud(FALSE, $users);
                $this->session->set_flashdata('success', 'Student/s Successfully Registered.');
                redirect(base_url().'user/upload_file');
            } else {
                $this->session->set_flashdata('error', 'You did not choose any account to register.');
                redirect(base_url().'user/upload_file');
            }
        }
                
        function register_emp() {
            if (isset($_POST['user']) && sizeof($_POST['user'])) {
              $users = array();
              $x = 0;
              foreach ($_POST['user'] as $user)  {
                  $user = str_replace("???"," ",$user);
                  $value = explode(",", $user);
                  $users[$x] = $value;
                  $x++;
              }
              $this->user_m->insert_emp(FALSE, $users);
                $this->session->set_flashdata('success', 'Employee/s Successfully Registered.');
                redirect(base_url().'user/upload_file');
            } else {
                $this->session->set_flashdata('error', 'You did not choose any account to register.');
                redirect(base_url().'users/upload_file', 'refresh');
            }
        }
        
        function view_reg_stud() {
            $data['body_id'] = 'admin_reg_stud';
            $data['title'] = 'Register Student';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_stud_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function view_reg_admin() {
            $data['body_id'] = 'admin_reg_admin';
            $data['title'] = 'Register Administrator';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_admin_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function view_reg_emp() {
            $data['body_id'] = 'admin_reg_emp';
            $data['title'] = 'Register Employee';
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/register_emp_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function reg_admin() {
            $data['body_id'] = 'admin_reg_admin';
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $this->user_m->insert_admin($data);
            $this->session->set_flashdata('success', 'Administrator Successfully Registered.');
            redirect(base_url().'register/admin');
        }
        
        function reg_stud() {
            $data['body_id'] = 'admin_reg_stud';
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $data['course'] = $this->input->post('course');
            $this->user_m->insert_stud(TRUE, $data);
            $this->session->set_flashdata('success', 'Student Successfully Registered.');
            redirect(base_url().'register/stud');
        }
        
        function reg_emp() {
            $data['body_id'] = 'admin_reg_emp';
            $data = array(); 
            $data['idno'] = $this->input->post('idno');
            $data['fname'] = $this->input->post('fname');
            $data['mname'] = $this->input->post('mname');
            $data['lname'] = $this->input->post('lname');
            $data['email'] = $this->input->post('email');
            $data['dept'] = $this->input->post('dept');
            $this->user_m->insert_emp(TRUE, $data);
            $this->session->set_flashdata('success', 'Employee Successfully Registered.');
            redirect(base_url().'register/emp');
        }
        
        function edit_user($idno) {
            $data['body_id'] = 'admin_users';
            $data['user'] = $this->user_m->get_user($idno);
            $temp = $this->user_m->get_user($idno);
            $data['error'] = $this->session->flashdata('error');
            $data['success'] = $this->session->flashdata('success');
            $data['title'] = 'Edit User';
            
            $this->form_validation->set_rules('fname', 'First Name', 'required|xss_clean');
            $this->form_validation->set_rules('mname', 'Middle Name', 'required|xss_clean');
            $this->form_validation->set_rules('lname', 'Last Name', 'required|xss_clean');
            $this->form_validation->set_rules('email', 'Email Address', 'required|xss_clean');
            $this->form_validation->set_rules('cd', 'Course/Department', 'required|xss_clean');
            
            if(isset($_POST) && !empty($_POST)) {
                if(isset($_POST['resetpass'])) {
                    $reset = $this->user_m->reset_password($idno, $this->input->post('email'));
                    if($reset) {
                        $this->session->set_flashdata('success',  'Password was successfully reset.');
                        redirect(base_url().'users');
                    } else {
                        $this->session->set_flashdata('error',  'An unknown error has occurred. Please check the email address if it is valid.');
                        redirect(base_url().'users');
                    }
                }else {
                  if(!is_null($temp['course'])) {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'course' => $this->input->post('cd'),
                        'password' => NULL
                    );
                  } else if(!is_null($temp['department'])) {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'department' => $this->input->post('cd'),
                        'password' => NULL
                    );
                  } else {
                    $info = array(
                        'idno' => $idno,
                        'fname' => $this->input->post('fname'),
                        'mname' => $this->input->post('mname'),
                        'lname' => $this->input->post('lname'),
                        'email' => $this->input->post('email'),
                        'password' => NULL
                    );
                  }
                    
                    if ($this->form_validation->run() === TRUE) {

                        $this->session->set_flashdata('success', 'User successfully updated.');
                        $this->user_m->update_user($info);
                        redirect(base_url().'users');
                    } 
                }
                
            }
            
            $this->load->view('administrator/fragments/header_v', $data);
            $this->load->view('administrator/fragments/user_navigation_v', $data);
            $this->load->view('administrator/edit_user_v', $data);
            $this->load->view('administrator/fragments/footer_v', $data);
        }
        
        function delete_user($idno) {
            $this->user_m->delete_user($idno);
            
            $this->session->set_flashdata('success', 'User successfully deleted.');
            
            redirect(base_url().'users');
        }
                
        function delete_user_update_role() {
            if(!empty($_POST['deleteB'])) {//delete
              if (isset($_POST['user']) && !empty($_POST)) {
                foreach ($_POST['user'] as $idno)  {
                  $user = $this->user_m->get_user_id($idno);
                  $this->user_m->delete_user($user->user_id);
                }
                $this->session->set_flashdata('success', 'User/s successfully deleted.');
                redirect(base_url().'users');
              } else {
                  $this->session->set_flashdata('error', 'You did not check any user to delete!');
                  redirect(base_url().'users');
              }
            } else {//update role
              $role_id = $_POST['role'];
              if (isset($_POST['user']) && !empty($_POST)) {
                  if(!is_null($role_id)) {
                      foreach ($_POST['user'] as $idno)  {
                        $user = $this->user_m->get_user_id($idno);
                        $this->user_m->update_user_role($user->user_id, $role_id);
                      }
                      $this->session->set_flashdata('success', 'Role successfully updated.');
                      redirect(base_url().'users');
                  } else {
                      $this->session->set_flashdata('error', 'You did not select a role!');
                      redirect(base_url().'users');
                  }
              } else {
                  $this->session->set_flashdata('error', 'You did not check any user to update!');
                  redirect(base_url().'users');
              }
            }
        }
    }
?>